import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import { store } from "/@/store";
import { notification } from "ant-design-vue";
import { useI18n } from "/@/locales/useI18n";

export const MANAGE_ROUTE_NAME = "manage";
//根路由数据
export const rootRouteInfo = [{ name: MANAGE_ROUTE_NAME, isInit: false, routeData: [] }];
export function resetRouter() {
  isInitAppData = false;
  rootRouteInfo.forEach((item) => {
    item.isInit = false;
    item.routeData.forEach((route: RouteRecordRaw) => {
      router.removeRoute(route.name as string);
    });
    item.routeData = [];
  });
}
let isInitAppData = false;
export function setIsInitAppData(isInit) {
  isInitAppData = isInit;
}
const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    name: "default",
    component: () => import(`../views/Home.vue`),
    children: [],
  },
  {
    path: `/${MANAGE_ROUTE_NAME}`,
    name: MANAGE_ROUTE_NAME,
    component: () => import(`../views/Home.vue`),
    children: [],
  },
  {
    path: "/login",
    name: "login",
    component: () => import(`../views/Login.vue`),
  },
];
function findRootRoute(path: string) {
  if (path === "/") {
    return rootRouteInfo[0];
  }
  for (let i = 0; i < rootRouteInfo.length; i++) {
    if (path.indexOf(`/${rootRouteInfo[i].name}`) === 0) {
      return rootRouteInfo[i];
    }
  }
  return null;
}
const router = createRouter({
  history: createWebHashHistory(),
  routes,
});
let curRootRoute: any = null;
router.beforeEach(async (to, from, next) => {
  const { path } = to;
  const target = findRootRoute(path);
  if (!target) {
    next();
    return;
  }
  store.dispatch("togglePageLoading", { loading: true });
  if (!isInitAppData) {
    isInitAppData = true;
    //加载应用数据
    const data = await store.dispatch("menu/getApplicationsByCurTenant");
    if (!data) {
      next({ name: "login" });
      return;
    }
  }
  if (curRootRoute) {
    if (target.name !== curRootRoute.name) {
      //切换应用 重新加载菜单数据
      resetRouter();
      // store.dispatch("menu/removeTabs");
    }
  }
  curRootRoute = target;
  if (!target.isInit) {
    target.isInit = true;
    const { t } = useI18n();
    notification.info({
      message: t("common.tip"),
      description: t("home.loadingMenu"),
      duration: null,
    });
    try {
      const { routeData } = await store.dispatch("menu/initAuthMenu", {
        rootRouteName: target.name,
      });
      target.routeData = routeData;
    } catch (err) {
    } finally {
      notification.destroy();
    }
    const routes = router.getRoutes();
    let finded = false;
    routes.forEach((route) => {
      if (route.path === path) {
        finded = true;
        next(route);
        return false;
      }
    });
    if (finded) {
      return;
    }
  }
  next();
});
router.afterEach(() => {
  store.dispatch("togglePageLoading", { loading: false });
});
export default router;
